What is lines-and-columns?
The lines-and-columns npm package is used to map between lines and columns to character offsets within a string, which is particularly useful when dealing with source code or any structured text format where line and column positions are commonly used.
What are lines-and-columns's main functionalities?
Index to Position
This feature allows you to convert a line and column position into a character offset index. It is useful when you have a line and column number and you want to find the corresponding position in a flat string.
{"const LinesAndColumns = require('lines-and-columns');\nconst lines = new LinesAndColumns('Hello\nWorld');\nconst location = lines.indexForLocation({ line: 1, column: 2 }); // returns 9"}
Position to Index
This feature allows you to convert a character offset index back into a line and column position. It is useful when you have an index in a string and you need to find out which line and column it corresponds to.
{"const LinesAndColumns = require('lines-and-columns');\nconst lines = new LinesAndColumns('Hello\nWorld');\nconst position = lines.locationForIndex(7); // returns { line: 1, column: 0 }"}
Other packages similar to lines-and-columns
columnify
The columnify package creates text-based columns suitable for console output, similar to how tables might be formatted in printed material. It differs from lines-and-columns in that it focuses on aligning columns of text rather than mapping positions within a text.
line-column
The line-column package provides similar functionality to lines-and-columns, allowing you to find the line and column position from a character offset and vice versa. It serves a similar purpose but may have different API details or performance characteristics.
line-numbers
The line-numbers package is used to prepend line numbers to a block of text. While it deals with lines in text, it does not provide the bidirectional mapping between line/column and character offset that lines-and-columns offers.
lines-and-columns
Maps lines and columns to character offsets and back. This is useful for parsers
and other text processors that deal in character ranges but process text with
meaningful lines and columns.
Install
$ npm install [--save] lines-and-columns
Usage
import { LinesAndColumns } from 'lines-and-columns'
const lines = new LinesAndColumns(
`table {
border: 0
}`
)
lines.locationForIndex(9)
lines.indexForLocation({ line: 1, column: 2 })
License
MIT